import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver, AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      resolvers: [ElementPlusResolver(), AntDesignVueResolver()],
      imports: ['vue', 'vue-router', 'pinia'],
      dts: 'src/auto-imports.d.ts',
    }),
    Components({
      resolvers: [
        ElementPlusResolver(), 
        AntDesignVueResolver({
          importStyle: false, // css in js
        })
      ],
      dts: 'src/components.d.ts',
      // 减少不必要的组件扫描，提高性能
      deep: true,
      // 只扫描 src 目录
      dirs: ['src/components', 'src/views'],
    }),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      'pdfjs-dist/legacy/build/pdf.js': 'pdfjs-dist/legacy/build/pdf.mjs',
      'pdfjs-dist/legacy/build/pdf': 'pdfjs-dist/legacy/build/pdf.mjs',
      'pdfjs-dist/legacy/build/pdf.worker.js': 'pdfjs-dist/legacy/build/pdf.worker.mjs',
      'pdfjs-dist/legacy/build/pdf.worker': 'pdfjs-dist/legacy/build/pdf.worker.mjs',
      'pdfjs-dist/build/pdf.worker.js': 'pdfjs-dist/legacy/build/pdf.worker.mjs',
      'pdfjs-dist/build/pdf.worker': 'pdfjs-dist/legacy/build/pdf.worker.mjs',
    },
  },
  server: {
    host: '0.0.0.0',
    port: 3000,
    hmr: {
      overlay: true, // 显示错误覆盖层
    },
    watch: {
      // 忽略某些文件变化，避免不必要的重新加载
      ignored: ['**/node_modules/**', '**/.git/**', '**/dist/**'],
    },
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
        rewrite: (path) => {
          // 如果路径不包含 /v1，自动添加
          if (!path.startsWith('/api/v1')) {
            return path.replace('/api', '/api/v1')
          }
          return path
        },
      },
    },
  },
  optimizeDeps: {
    // 预构建依赖，避免运行时重新构建
    include: [
      'echarts/core',
      'echarts/renderers',
      'echarts/charts',
      'echarts/components',
      'vue-echarts',
      'vue',
      'vue-router',
      'pinia',
      'element-plus',
      'ant-design-vue'
    ],
    // 排除某些依赖，避免不必要的重新构建
    exclude: [],
    // 强制重新构建（仅在需要时使用）
    // force: false,
  },
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler' // or "modern"
      }
    }
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    chunkSizeWarningLimit: 1500,
  },
})